package com.yc.atm;

import com.google.gson.Gson;

import java.io.IOException;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Scanner;

public class BankTask implements Runnable {
    private Socket socket;
    private Bank b;
    private boolean flag;
    public BankTask(Socket s,Bank b){
        this.socket=s;
        this.b=b;
        this.flag=true;
    }
    @Override
    public void run() {
        try (
                //因为要用到tr..resource直接关闭socket，所以要将socket重新在try注册
                Socket s = this.socket;
                Scanner reader = new Scanner(s.getInputStream());
                PrintWriter pw = new PrintWriter(s.getOutputStream());) {
            while (flag && !Thread.currentThread().isInterrupted()) {
                //客户端是否没有传数据，如没有传则结束
                if (!reader.hasNext()){
                    System.out.println("atm客户端"+s.getRemoteSocketAddress()+"掉线了");
                    break;
                }
                //如果有信息则取出
                String command=reader.next();//next()读第一个部分，而没有读取一行。
                BankAccount ba=null;
                JsonModel<BankAccount>jm=new JsonModel<>();
                //命令模式：
                if ("DEPOSIT".equals(command)){
                    int id=reader.nextInt();
                    double money=reader.nextDouble();
                    ba=b.deposite(id,money);
                }else if ("WITHDRAW".equals(command)){
                    int id=reader.nextInt();
                    double money=reader.nextDouble();
                    ba=b.withdraw(id,money);
                }else if ("BALANCE".equals(command)){
                    int id=reader.nextInt();
                    ba=b.search(id);
                }else if ("QUIT".equals(command)){
                    System.out.println("atm客户端要求主动断开.."+s.getRemoteSocketAddress());
                    break;
                }else {
                    //pw.println("错误指令“);
                    jm.setCode(0);
                    jm.setErrorMsg("错误指令");
                    Gson g=new Gson();
                    String jsonString=g.toJson(jm);
                    pw.println(jsonString);
                    pw.flush();
                    continue;
                }
                //TODO:将基本字符串改为Json，这样数据丰富
                //pw.println(ba.getID()+""+ba.getBalance);
                jm.setCode(1);
                jm.setObj(ba);
                Gson g=new Gson();
                String jsonString=g.toJson(jm);
                pw.println(jsonString);
                pw.flush();
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }
    }
